// @charset "utf-8";
// ajax
define(function (require, exports, module) {
	var Backbone = require('backbone');
	var AjaxBaseModel = Backbone.Model.extend({
		defaults : {
			errorcode : '',
			errormsg : '',
			result : ''
		},
		url : '',
		callback : '',
		type : 'get',
		dataType : 'json',
		dataparse : '',

		request : function (data) {
			var self = this;
			data = data || {};
			self._request(data, self.url, self.callback);
		},
		requestEx : function (data, url, callback) {
			var self = this;
			data = data || {};
			self._request(data, url, callback);
		},
		_request : function (data, url, callback) {
			$.support.cors = true;
			var self = this;

			$.ajax({
				url : url,
				data : data,
				type : self.type,
				dataType : self.dataType,
				success : function (result) {
					if ('' !== self.dataparse) {
						result = self.dataparse(result);
					}
					self.set(result);
					if ('' !== callback) {
						callback(result);
					}
				},
				error : function () {
					self.set({
						errorcode : -777,
						errormsg : '请求失败，请稍后再试',
						result : ''
					});
					if ('' !== callback) {
						callback();
					}
				}
			});
		},
		sortData : function (sortBy, sortWay, list, page) {
			var self = this;
			list = list.sort(self.sortTableFun(sortBy, sortWay));
			return self.getPageData(page, 4000, list);
		},
		sortTableFun : function (sortBy, srotWay) {
			var ordAlpah = (srotWay == 'asc') ? '>' : '<';
			// var sortFun = new Function('a', 'b', 'return a.' + sortBy + ordAlpah + 'b.' + sortBy + ' ? 1 : -1');
			var sortFun = new Function('a', 'b', 'if(isNaN(parseFloat(a.' + sortBy + '))){return 1;}if(isNaN(parseFloat(b.' + sortBy + '))){return -1;} return parseFloat(a.' + sortBy + ')' + ordAlpah + 'parseFloat(b.' + sortBy + ') ? 1 : -1');
			return sortFun;
		},
		getPageData : function (page, pageSize, list) {
			var index = 1;
			var pageData = [];

			for (var i in list) {
				if (page === Math.ceil(index/pageSize)) {
					pageData.push(list[i]);
				}
				if (page < Math.ceil(index/pageSize)) {
					index++;
					break;
				}
				index++;
			}

			return {
				data : pageData,
				length : list.length
			};
		},
		searchData : function (keywords, searchBy, list) {
			var result = [];
			for (var i in list) {
				if ('all' === keywords || -1 !== (''+list[i][searchBy]).indexOf(keywords)) {
					result.push(list[i]);
				}
			}

			return result;
		}
	});

	module.exports = AjaxBaseModel;
});